// 函数组件
import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import { message, Input, Select, Space, Button, Table, Pagination } from 'antd';
import "../goods/css/GoodRecycle.less"
import "../../css/public.less"
import type { ColumnsType } from 'antd/es/table';
import type { TableRowSelection } from 'antd/es/table/interface';
import { DownOutlined, UpOutlined, SyncOutlined } from '@ant-design/icons';
import { ConfigProvider, Modal } from 'antd';
import zh_CN from 'antd/es/locale/zh_CN';
import { ExclamationCircleFilled } from '@ant-design/icons';
import { delDelByIds,selectDel,updateStatus } from "../.././../api/lys"

interface DataType {
  id?: number, // 序号
  brandName: string
  categoryName: string
  goodsBrandId: number
  goodsCategoryId: number
  goodsChildId: number
  goodsDesc: string
  goodsId: number
  goodsImg: string
  goodsName: string
  goodsOnTime: string
  goodsPay: string
  goodsPost: string
  goodsPriceRange: string
  goodsRec: string
  goodsSell: string
  goodsSer: string
  goodsSernum: string
  goodsShopId: number
  goodsStatus: string
  goodsSupplieId: number
  goodsTrail: string
}

interface Obj {
  value: string,
  id: number,
  label: string
}





function GoodRecycle() {
  //checkBox选中数据
  const [selectedRow, setSelectedRow] = useState<number[]>([]);
  const [data, setData] = useState<any[]>([])
  const [isShow, setIsShow] = useState<boolean>(true)
  const [keyword, setKeyword] = useState<string>("")
  const [dustbin, setDustbin] = useState<string>("")
  const [brand, setBrand] = useState<string>("")
  const [messageApi, contextHolder] = message.useMessage();
  //页码数据
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(3)
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [count, setCount] = useState<number>()
  const [type, setType] = useState<any[]>([])
  const [brand2, setBrand2] = useState<any[]>([])
const [recordId,setRecordId] = useState<any[]>([])


  useEffect(() => {
    goodsList(page, pageSize)
  }, [page, pageSize])

  //对象数组去重
  const deWeightThree = (arr: any) => {
    let map = new Map();
    for (let item of arr) {
      if (!map.has(item.value)) {
        map.set(item.value, item);
      }
    }
    return [...map.values()];
  }



  const goodsList = (pages: number | undefined, pageSizes: number | undefined) => {
    selectDel({
      "limit": pageSizes,
      "page": pages,
      "goodsStatus": "6"
    }).then((res) => {
      console.log("全部商品数据", res.data);
      if (res.code == "200") {

        let arr: any[] = []
        let brandArr: any[] = []
        res.data.data.map((item: any) => {
          arr.push(
            {
              value: item.goodsCategoryId,
              id: item.goodsCategoryId,
              label: item.categoryName
            }
          )
          brandArr.push(
            {
              value: item.goodsBrandId,
              id: item.goodsBrandId,
              label: item.brandName
            }
          )
        })

        let arr3 = deWeightThree(arr)
        let arr4 = deWeightThree(brandArr)
        setType(arr3)
        setBrand2(arr4)
        setData(res.data.data)
        addKey(res.data.data)
        setCount(res.data.totalByStatus)
      }
    })
  }

  const onChangePage = (page: any, pageSize: any) => {
    console.log("页码", page, pageSize);
    setPage(page)
    setPageSize(pageSize)
  }

  const addKey = (data: any) => {
    data.map((item: any) => {
      item.id = Math.floor(Math.random() * 10000000000)
      return item
    })
  }



  const rowSelection = {
    onChange: (key: any, row: DataType[]) => {

      let checkArr: any = [];
      row.map(item => {
        checkArr.push(item.goodsId)
      })
      setSelectedRow(checkArr)
     
    },
  }

  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      dataIndex: 'goodsId',
    },
    {
      title: '商品图片',
      dataIndex: 'goodsImg',
      render: (_, record) => (
        <Space size="middle">
          <img width={50} height={50} src="" alt="" />
        </Space>
      )
    },
    {
      title: '商品名称',
      dataIndex: 'goodsName',
    },
    {
      title: '货号',
      dataIndex: 'goodsSernum',
    },
    {
      title: '价格',
      dataIndex: 'goodsPriceRange',
    },
    {
      title: '分类',
      dataIndex: 'goodsDesc',
    },
    {
      title: '操作',
      dataIndex: 'shop_handle',
      render: (_, record) => (
        <div>
          <button className='edit' onClick={()=>oneHuanYuan(record)}>还原</button>
          <button className='del' onClick={() => delAudit(record)}>删除</button>
        </div>
      )
    },
  ];

  const { confirm } = Modal;

  const updateStatu = (obj:any) => {
    updateStatus(obj).then((res) => {
      console.log("res11111111", res);
      if(res.code=="200"){
        console.log(res.msg);
        goodsList(page,pageSize)
      }
    }).catch((err)=>{
      console.log("出错了");
      
    })
}

const delDelById = (obj:any) => {
  delDelByIds(obj).then((res) => {
    console.log("res11111111", res);
    if(res.code=="200"){
      console.log(res.msg);
      goodsList(page,pageSize)
    }
  }).catch((err)=>{
    console.log("出错了"); 
  })
}



  //批量删除
  const showConfirm = () => {
    if (selectedRow.length) {
      confirm({
        centered: true,
        cancelText: "取消",
        okText: "确定",
        title: '是否全部删除',
        icon: <ExclamationCircleFilled />,
        content: '删除选中项，一项或多项',
        onOk() {
          delDelById(
            selectedRow,
          )
          console.log("selectedRow",selectedRow);
          console.log('OK');
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    } else {
      console.log('请至少选择一个');
      messageApi.open({
        type: 'warning',
        content: '请至少选择一个',
      });
    }
  };
  //单个删除
  const delAudit = (record: any) => {
    confirm({
      centered: true,
      cancelText: "取消",
      okText: "确定",
      title: '是否删除选中项',
      icon: <ExclamationCircleFilled />,
      content: '',
      onOk() {
        console.log('OK');
        delDelById(
          [record.goodsId]
        )

      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }


  //筛选
  const filterGoods = () => {
    let obj = {
      "goodsBrandId": brand,
      "goodsCategoryId": dustbin,
      "goodsName": keyword,
      "limit": pageSize,
      "page": page
    }
    selectDel(obj).then((res) => {
      // console.log("res", res);
      let arr4 = deWeightThree(res.data.data)
      setData(arr4)

    })
  }

  //批量还原
  const allHuanYuan = ()=>{
    if (selectedRow.length) {
      confirm({
        centered: true,
        cancelText: "取消",
        okText: "确定",
        title: '是否全部还原',
        icon: <ExclamationCircleFilled />,
        content: '还原选中项，一项或多项',
        onOk() {
          updateStatu({ 
            "ids": selectedRow,
            "status": "5"
          })
          console.log('OK');
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    } else {
      console.log('请至少选择一个');
      messageApi.open({
        type: 'warning',
        content: '请至少选择一个',
      });
    }

  }

  //单个还原
  const oneHuanYuan=(record:any)=>{


    console.log("record",record);
  
    
    confirm({
      centered: true,
      cancelText: "取消",
      okText: "确定",
      title: '是否还原',
      icon: <ExclamationCircleFilled />,
      content: '',
      onOk() {
        updateStatu({ 
          "ids": [record.goodsId],
          "status": "5"
        })
        console.log("recordId",recordId);
        console.log('OK');
      },
      onCancel() {
        console.log('Cancel');
      },
    });

  }

  return (
    <div className='GoodRecycle'>
      {contextHolder}
      {/* 头部标题 */}
      <div className='page-top'>
        <div className='page-title'>
          <p>商品回收站</p>
        </div>
      </div>

      <div className='page-context'>

        {/* 筛选框 */}
        <div className='search-input'>
          <div style={{ display: 'flex', justifyContent: 'space-between', height: "50px" }}>
            <p>商品筛选</p>
            {isShow ? <UpOutlined onClick={() => {
              setIsShow(false)
            }} /> : <DownOutlined onClick={() => {
              setIsShow(true)
            }} />}
          </div>
          {isShow ?
            <div style={{ height: "180px" }}>
              <div className='header1-top'>

                {/* 关键词 */}
                <div>
                  <span>关键词</span><Input onChange={(e: any) => {
                    setKeyword(e.target.value)
                    console.log(e.target.value);
                  }} placeholder="商品名称/商品货号" />
                </div>
                {/* 分类 */}
                <div>
                  <span>分类</span>
                  <div> <Select allowClear placeholder="请选择类别"
                    style={{ width: 120 }}
                    onChange={(value: string) => {
                      setDustbin(value)
                      console.log(value);
                    }}
                    options={type} />
                  </div>

                </div>
                {/* 品牌 */}
                <div>
                  <span>品牌</span>
                  <div> <Select allowClear placeholder="请选择品牌"
                    style={{ width: 120 }}
                    onChange={(value: string) => {
                      setBrand(value)
                      console.log(value);
                    }}
                    options={brand2}
                    autoFocus={false} />
                  </div>

                </div>

              </div>

              <div className='button-box'><button className='reset'>重置</button><button className='filter' onClick={filterGoods}>筛选</button></div>

            </div> : ""}
        </div>

        {/* 表格 */}
        <div className='data-list'>
          <div>
            <p>数据列表</p>
            <div>
            <button className='add huanyuan' onClick={allHuanYuan}>批量还原</button>
            <button className='batch-del' onClick={showConfirm}>批量删除</button>
            </div>
            
          </div>
          {/* 表格 */}
          <div className='table-box'>
            <ConfigProvider locale={zh_CN}>
              <Table rowSelection={rowSelection} columns={columns} dataSource={data}
                scroll={{ y: 444 }}
                rowKey={item => String(item.id)}
                pagination={{
                  position: ['bottomCenter'],
                  total: count,
                  defaultPageSize: 3,
                  pageSizeOptions: [3, 5, 10, 15],
                  showQuickJumper: true,
                  showSizeChanger: true,
                  onChange: onChangePage
                }}
              />
            </ConfigProvider>


          </div>
        </div>

      </div>
    </div>
  )
}

export default GoodRecycle